<template>
<div class="select-field-box">
    <div class="some-data-count">
        <div class="info-top-box">
            <span class="s-d-c-item"><span class="desc-tip">行数：</span>{{detail.dataSet.rows}}</span>
            <span class="s-d-c-item"><span class="desc-tip">列数：</span>{{detail.dataSet.cols}}</span>
            <span class="s-d-c-item"><span class="desc-tip">大小：</span>{{getFileSize}}</span>
            <span class="s-d-c-item"><span class="desc-tip">创建人：</span>{{detail.table.createOper}}</span>
            <el-radio-group v-if="detail.enableDataSummary" class="s-d-c-item" v-model="type" size="mini">
                <el-radio-button :label="index" v-for="(item, index) in types" :key="index">
                    <el-tooltip effect="dark" :content="item.title" placement="top-start">
                        <i :class="`iconfont ${item.icon}`"></i>
                    </el-tooltip>
                </el-radio-button>
            </el-radio-group>
            <el-button type="default" @click="handleSelectField">已选择{{count}}个字段</el-button>
        </div>
    </div>
    <div class="dialog-con">
        <div class="d-c-left" :style="detail.enableDataSummary?'width:calc(100% - 280px)':'width:100%'">
            <vxe-table v-if="!detail.enableDataSummary" align="center" ref="xTable" resizable show-header-overflow height="500" border>
                <template v-for="(item, index) in tableColums">
                    <vxe-table-column :key="index" :field="item" :title="item" width="150" show-overflow>
                        <template v-slot:header="{ column }">
                            <span class="field-name">{{item}}</span>
                            <miss-value v-if="detail.dataSet.hasNullCols && detail.dataSet.hasNullCols.includes(item)"></miss-value>
                            <div class="filed-type" v-if="detail.dataSet.type">{{getType(item)}}</div>
                        </template>
                    </vxe-table-column>
                </template>
            </vxe-table>
            <vxe-table v-else align="center" ref="xTable" @header-cell-click="handerClickHeader" resizable show-header-overflow height="500" border highlight-hover-column highlight-current-column>
                <template v-for="(item, index) in tableColums">
                    <vxe-table-column :key="index" :field="item" :title="item" width="150" show-overflow>
                        <template v-slot:header="{ column }">
                            <span class="field-name">{{item}}</span>
                            <miss-value v-if="detail.dataSet.hasNullCols && detail.dataSet.hasNullCols.includes(item)"></miss-value>
                            <div class="filed-type" v-if="detail.dataSet.type">{{getType(item)}}</div>
                        </template>
                        <template v-slot="{ row }">
                            <template v-if="row.type==='chart'">
                                <div style="padding-top:5px;">
                                <ve-histogram v-if="type === 0" :colors="['#3F9EFF']" :extend="extend" width="100%" height="60px" :data="chartInfo.histogramInfo[item]"></ve-histogram>
                                <box-plot v-if="type === 1" :id="`boxPlot-${item}`" :data="chartInfo.boxplotInfo[item]"></box-plot>
                                </div>
                            </template>
                            <template v-else>{{row[item]}}</template>
                        </template>
                    </vxe-table-column>
                </template>
            </vxe-table>
        </div>
        <div v-if="detail.enableDataSummary" class="d-c-right">
            <title-bar title="字段统计信息" :border="true"></title-bar>
            <div class="record-info scroll-bar">
                <div class="filed-box" v-show="item[0].value !== null" v-for="(item, key, i) in chartInfo.staticInfo[value]" :key="i">
                    <span class="desc-record">{{key}}</span>
                    <span>{{item[0].value}}</span>
                </div>
                <div v-if="noRecordInfo[value]" class="tips-center">
                    <span>暂无数据</span>
                </div>
            </div>
            <title-bar title="数据可视化" :border="true"></title-bar>
            <ve-histogram v-if="type === 0 && chartInfo.histogramInfo[value]" :colors="['#3F9EFF']" :extend="histogramExtend" :legend-visible="true" :data-empty="chartInfo.histogramInfo[value].rows.length===0" width="100%" height="400px" :data="chartInfo.histogramInfo[value]"></ve-histogram>
            <box-plot v-if="type === 1" ref="boxPlot" id="boxPlot" :data="chartInfo.boxplotInfo[value]"></box-plot>
            <div v-show="!chartInfo.boxplotInfo[value] && type === 1" class="tips-center" style="height:400px;">
                <span>暂无数据</span>
            </div>
        </div>
    </div>
    <multiple-select-field v-if="multiple.show" :data="multiple" @save="handleSave" v-model="multipleVal"></multiple-select-field>
</div>
</template>

<script>
import TitleBar from '@/components/TitleBar'
import BoxPlot from './BoxPlot'
import MissValue from '@/components/MissValue'
import MultipleSelectField from '@/components/MultipleSelectField'
import { changeWindowSize } from '@/js/tool'
export default {
    name: 'detailDialog',
    props: {
        detail: {
            type: Object
        }
    },
    components: {
        TitleBar,
        BoxPlot,
        MissValue,
        MultipleSelectField
    },
    computed: {
        getFileSize () {
            let size = this.detail.table.dataFileSize
            if (size < 1024) {
                size = size + 'B'
            } else if (size < 1048576) {
                size = parseInt(size / 1024) + 'K'
            } else if (size < 1073741824) {
                size = parseInt(size / 1048576) + 'M'
            } else if (size < 1073741824 * 1024) {
                size = parseInt(size / 1073741824) + 'G'
            }
            return size
        }
    },
    data () {
        return {
            count: 0,
            loadSign: true,
            multipleVal: '',
            multiple: {
                title: '选择字段',
                show: false,
                isNumber: false, // 多输入列选择框，多个列选择弹窗，只能选择数值类型的
                data: []
            },
            dom: null,
            boxPlotData: null,
            histogramExtend: {
                dataZoom: [{
                    type: 'inside'
                }],
                grid: {
                    left: '10%',
                    right: '10%'
                },
                series: {
                    showSymbol: false,
                    barMaxWidth: 20
                }
            },
            extend: {
                series: {
                    showSymbol: false,
                    barMaxWidth: 30
                },
                legend: {
                    show: false
                },
                yAxis: {
                    show: false
                },
                xAxis: {
                    show: false
                },
                tooltip: {
                    show: false
                }
            },
            value: '',
            type: 0,
            types: [
                { icon: 'icon-zhuzhuangtu', title: '直方图' },
                { icon: 'icon-xiangxingtu', title: '箱线图' }
            ],
            chartData: {
                columns: [],
                rows: []
            },
            tableColums: [],
            recordInfo: null,
            showList: [],
            noRecordInfo: {},
            chartInfo: {
                staticInfo: {},
                histogramInfo: {},
                boxplotInfo: {}
            }
        }
    },
    mounted () {
        this.init()
    },
    methods: {
        getType (item) {
            const { header, type } = this.detail.dataSet
            return type[header.indexOf(item)]
        },
        handleSelectField () {
            this.multiple.show = true
        },
        setColumnsShowHide (values) {
            let arr = this.tableColums
            let newArr = []
            let list = []
            this.count = 0
            for (let i = 0; i < arr.length; i++) {
                newArr[i] = { field: arr[i], visible: false }
                for (let n = 0; n < values.length; n++) {
                    if (values[n] === arr[i]) {
                        newArr[i].visible = true
                        list.push(newArr[i])
                        this.count++
                    }
                }
            }
            this.showList = list
            this.$refs.xTable.reloadCustoms(newArr)
            if (this.detail.enableDataSummary) {
                this.handerClickHeader({ column: null })
            }
        },
        handleSave (t, val) {
            let values = (val && val.split(',')) || []
            if (values.length > 0) {
                this[t].show = false
                this.setColumnsShowHide(values)
            } else {
                this.$message.error('请先选择字段')
            }
        },
        // 获取表格数据
        init () {
            const { dataSet: { header, type, records }, dataSetGraphInfo, dataSetStatisticInfo, enableDataSummary } = this.detail
            this.tableColums = header
            this.count = header.length
            let multipleData = []
            let newArr = []
            this.multipleVal = header.join(',')
            if (enableDataSummary) {
                for (let i = 0; i < dataSetStatisticInfo.length; i++) {
                    let item = dataSetStatisticInfo[i]
                    for (const key in item) {
                        let arr = []
                        item[key].forEach((v, n) => {
                            arr[n] = { key: header[n], value: v }
                        })
                        item[key] = arr
                    }
                }
            }
            for (let i = 0; i < header.length; i++) {
                if (enableDataSummary) {
                    dataSetGraphInfo[i].key = header[i]
                }
                multipleData[i] = { name: header[i], type: type[i] }
            }
            this.multiple.data = multipleData
            for (let i = 0; i < records.length; i++) {
                let newObj = {}
                for (let n = 0; n < header.length; n++) {
                    let val = records[i][n]
                    if (typeof val === 'object') {
                        val = JSON.stringify(val)
                    }
                    newObj[header[n]] = val
                }
                newArr[i] = newObj
            }
            if (enableDataSummary) {
                newArr.unshift({ type: 'chart' })
            }
            this.getChartInfo(newArr, enableDataSummary)
            if (enableDataSummary) {
                this.showList = [{ field: this.tableColums[0] }]
                this.handerClickHeader({ column: null })
            }
        },
        // 点击表头单元格
        handerClickHeader ({ column }) {
            this.value = !column ? this.showList[0].field : column.property
            setTimeout(() => {
                if (!column) {
                    let obj = this.$refs.xTable.getColumnByField(this.value)
                    this.$nextTick(() => {
                        this.$refs.xTable.setCurrentColumn(obj)
                    })
                }
                if (this.type === 1) {
                    this.$refs.boxPlot.init()
                }
                changeWindowSize()
            }, 500)
        },
        // 获取图表信息
        getChartInfo (data, flag) {
            if (flag) {
                let arr = this.tableColums
                let staticInfo = {}
                let histogramInfo = {}
                let boxplotInfo = {}
                for (let i = 0; i < arr.length; i++) {
                    let val = arr[i]
                    staticInfo[val] = this.getStaticInfo(val)
                    histogramInfo[val] = this.getHistogram(val)
                    boxplotInfo[val] = this.getBoxPlot(val)
                }
                this.chartInfo = { staticInfo, histogramInfo, boxplotInfo }
            }
            this.$nextTick(() => {
                this.$refs.xTable.loadData(data)
            })
        },
        // 获取统计信息
        getStaticInfo (val) {
            let flag = true
            let list = this.detail.dataSetStatisticInfo || []
            let obj = {}
            for (let i = 0; i < list.length; i++) {
                for (const key in list[i]) {
                    obj[key] = list[i][key].filter(v => val === v.key)
                    if (obj[key][0].value !== null) {
                        flag = false
                    }
                }
            }
            this.noRecordInfo[val] = flag
            return obj
        },
        // 获取直方图
        getHistogram (val) {
            let rows = this.getRows('直方图', val)
            if (rows.length) {
                for (let k in rows) {
                    rows[k][val] = isNaN(rows[k][val]) ? rows[k][val] : parseFloat(rows[k][val]).toFixed(4)
                }
            }
            return {
                columns: [val, 'frequency'],
                rows
            }
        },
        // 获取箱线图
        getBoxPlot (val) {
            return this.getRows('箱线图', val)
        },
        getRows (str, val) {
            let rows = []
            let arr = this.detail.dataSetGraphInfo || []
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].key === val) {
                    rows = arr[i][str] || []
                    break
                }
            }
            if (str === '箱线图' && rows.length === 0) {
                rows = null
            }
            return rows
        }
    }
}
</script>

<style lang="less">
.select-field-box {
    .info-top-box {
        display: flex;
        align-items: center;
        justify-items: center;
    }
    .filed-type {
        padding-top: 5px;
        color: #888888;
        text-align: center;
    }
    .selected-cell {
        background: #2680EB;
        span {
            color: #fff;
        }
    }

    .table-head-style .table-head-cell .cell {
        cursor: pointer;
    }

    .icon-btns {
        width: 80px;
        text-align: center;
        font-size: 12px;

        .btns-title {
            padding-top: 60px;
            padding-bottom: 5px;
        }

        i {
            font-size: 20px;
            cursor: pointer;
            padding: 0 3px;
        }
    }

    .chart div {
        font: 10px sans-serif;
        background-color: steelblue;
        text-align: right;
        padding: 3px;
        margin: 1px;
        color: white;
    }

    .dialog-con {
        display: flex;

        .btns-icons > div {
            color: #2680EB;
        }

        .icon-xiangxingtu:hover + div {
            &::after {
                content: '切换为箱线图';
            }
        }

        .icon-zhuzhuangtu:hover ~ div {
            &::after {
                content: '切换为直方图';
            }
        }

        .d-c-right {
            height: 550px;
            overflow-y: auto;
            overflow-x: hidden;
            width: 400px;
            padding-left: 5px;
        }

        .record-info {
            height: 250px;
            align-items: flex-start;
            display: flex;
            justify-content: center;
            flex-direction: column;
            overflow: auto;
            .filed-box {
                display: flex;
                line-height: 32px;
                font-size: 12px;
            }

            .desc-record {
                width: 120px;
                display: inline-block;
                padding-left: 20px;
            }
        }
        .tips-center {
            height: 100%;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            span {
                font-size: 14px;
                color: #888888;
            }
        }
        .table-head-tips {
            display: inherit;
            height: 16px;
            line-height: 16px;
            width: 100%;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .preview-table .el-table__header th {
            background: #f5f5f5;
        }
        .data-preview-pagination {
            text-align: right;
            margin-top: 10px;
        }
    }
}
</style>
